package com.coding.service.impl;

import com.coding.base.pojo.BaseModel;
import com.coding.base.util.CreateOssUtil;
import com.coding.dao.OssImagesDao;
import com.coding.pojo.OssImages;
import com.coding.service.OssImagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @auther wangchenghao
 * @date 2020/7/25
 **/
@Service
public class OssImagesImpl implements OssImagesService {

    @Autowired
    OssImagesDao ossImagesDao;
    @Override
    public void addImg(OssImages ossImages, BaseModel model) throws Exception {
        if (ossImages.getImage_url() == null) {
            model.setFailure("上传图片失败");
            return;
        }
        if (ossImagesDao.insert(ossImages) == 1) {
            model.setSucceed("新增图片资源成功", ossImagesDao.selectByPrimaryKey(ossImages.getImage_id()));
        } else {
            model.setFailure("新增图片资源失败");
        }
    }

    @Override
    public void upImg(OssImages ossImages, BaseModel model) throws Exception {

    }

    @Override
    public void deleteImg(OssImages ossImages, BaseModel model) throws Exception {

    }

    @Override
    public void getImg(OssImages ossImages, BaseModel model) throws Exception {

    }

    @Override
    public void getImgbyid(int imageid, BaseModel baseModel) throws Exception {
        OssImages ossImages=ossImagesDao.selectByPrimaryKey(imageid);
        if (ossImages.getImage_url()!=null) {
            baseModel.setSucceed("获取图片成功", ossImages);
        } else {
            baseModel.setFailure("获取图片失败");
        }
    }

    @Override
    public void setOssimage(MultipartFile file, BaseModel model) throws Exception {
        if (file == null || file.getSize() <= 0) {
            model.setFailure("file不能为空");
            return ;
        }
        //上传图片至oss
        OssImages ossImages= CreateOssUtil.createOss(file);
        addImg(ossImages,model);
    }

    @Override
    public void getImagebyname(String name, BaseModel model) throws Exception {
        List<OssImages> ossImagesList=ossImagesDao.selectByName(name);
        if (ossImagesList.size()>0){
            model.setSucceed("查询图片列表成功",ossImagesList);
        }else {
            model.setFailure("没查询到"+name+"相关图片");
        }
    }

    @Override
    public void getImagebytag(String tag, BaseModel model) throws Exception {
        List<OssImages> ossImagesList=ossImagesDao.selectByTag(tag);
        if (ossImagesList.size()>0){
            model.setSucceed("查询图片列表成功",ossImagesList);
        }else {
            model.setFailure("没查询到"+tag+"相关图片");
        }
    }

    @Override
    public OssImages setImage(MultipartFile file) throws Exception {
        if (file == null || file.getSize() <= 0) {
            return null;
        }
        //上传图片至oss
        OssImages ossImages= CreateOssUtil.createOss(file);
        return ossImages;
    }
}
